package com.situ.crm.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.situ.crm.pojo.User;
import com.situ.crm.service.IUserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class CustomRealm extends AuthorizingRealm {
    @Autowired
    private IUserService userService;

    // subject.login(token);
    // UsernamePasswordToken implements  RememberMeAuthenticationToken extends AuthenticationToken
    /*public interface AuthenticationToken extends Serializable {
        Object getPrincipal();// 用户名

        Object getCredentials();// 密码
    }*/
    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //String username = token.getUsername();
        //char[] password = token.getPassword();
        String name = (String) authenticationToken.getPrincipal();

        // 根据用户名去数据库中查询是不是有这个名字的用户
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("name", name);
        List<User> list = userService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            throw new UnknownAccountException("用户名不存在");
        }
        User user = list.get(0);

        // 上面只是做用户名的校验，密码的校验的在下面代码中shiro会自动帮我们做
        SimpleAuthenticationInfo simpleAuthenticationInfo
                = new SimpleAuthenticationInfo(name, user.getPassword(), getName());
        return simpleAuthenticationInfo;
    }

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取登录的用户名
        String name = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 去数据库根据用户名查询这个用户所有的角色信息
        List<String> roles = userService.selectRolesByUserName(name);
        simpleAuthorizationInfo.addRoles(roles);
        // 去数据库根据用户名查询这个用户所有的权限信息
        List<String> permissions = userService.selectPermissionsByUserName(name);
        simpleAuthorizationInfo.addStringPermissions(permissions);

        return simpleAuthorizationInfo;
    }


}
